<template>
  <div class="team">
    <!-- 上面的部分 -->
    <div class="top">
      <div>
        <!-- 伪类部分 -->
        <div>
          <span class="top-team">团队管理</span>
        </div>
        <div style="margin-top: 20px; margin-left: 5px">
          <div class="menu-wrapper">
            <el-menu style="width: 1140px" :default-active="activeIndex" class="el-menu-demo" mode="horizontal"
              :ellipsis="false" @select="handleSelect">
              <el-menu-item class="flex-grow" style="text-align: left" index="0">
                我管理的团队
              </el-menu-item>
              <el-menu-item index="1" class="flex-grow" style="text-align: left">
                我加入的团队
              </el-menu-item>

              <el-menu-item style="margin-left: 450px">
                <el-button type="primary" @click="addTeam">新增医生团队</el-button>
              </el-menu-item>
              <el-menu-item>
                <el-button type="primary" @click="dialogVisible = true">申请加入团队</el-button>
              </el-menu-item>
              <el-menu-item>
                <el-button @click="daochu">导出</el-button>
              </el-menu-item>
            </el-menu>
          </div>
        </div>
        <!-- 搜索部分的input框 -->
        <div class="team-search">
          <div style="margin-right: 30px">
            <span style="margin-right: 10px">所属机构</span>
            <el-select v-model="value" class="m-2" placeholder="请选择" size="large" @change="getLabel">
              <el-option v-for="(item, index) in arr" :key="index" :label="(item.name as string)" :value="item.id" />
            </el-select>
          </div>

          <div class="team-keywords">
            <el-input class="keywords-input" placeholder="请输入关键字" size="large" v-model="keywords_1">
              <template #suffix>
                <el-icon class="el-input__icon" @click="searchByKeywords">
                  <search />
                </el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </div>
    <!-- 中间的部分 -->
    <div class="team-middle">
      <!-- table表格部分 -->

      <el-table :data="tabledata" style="width: 100%">
        <el-table-column property="number" label="编号" align="center" />
        <el-table-column align="center" label="头像">
          <template #default="{ row }">
            <img :src="'http://127.0.0.1:3000/' + row.picture" style="width: 40px" />
          </template>
        </el-table-column>

        <el-table-column property="tname" label="团队名称" align="center" />
        <el-table-column property="dname" label="团队长" align="center" />
        <el-table-column label="团队标签" align="center">
          <template #default="{ row }">
            <el-tag v-for="item in row.labelArr" :key="item.id" class="mx-1" effect="light" round size="middle">
              {{ item.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="oname" label="所属机构" align="center" />
        <el-table-column property="score" label="评分" align="center" />
        <el-table-column property="signCount" label="签约人数" align="center" />
        <el-table-column label="状态" property="flag">
          <template #default="{ row }">
            <el-switch v-model="row.flag" inline-prompt active-text="启用" inactive-text="禁用"
              @click="changeTeamStatus(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <span class="origation-edit" @click="TeamDetail(scope.row)">查看团队</span>
            <span class="origation-del" @click="delTeam(scope.row)">解散团队</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部的部分 -->
    <div class="fenyeqi">
      <Fenye :total="total" @changepageSize="getPageSize" @changeCurrentPage="getCurrentPage"></Fenye>
    </div>
    <!-- 遮罩层 -->
    <el-dialog v-model="dialogVisible" title="申请加入团队" width="70%" :before-close="handleClose">
      <div style="display: flex; justify-content: space-between">
        <el-input placeholder="请输入团队名称或团队编号" v-model="value3"></el-input>
        <el-button>搜索</el-button>
      </div>
      <div style="margin: 10px">
        <el-table :data="tabledata" style="width: 100%">
          <el-table-column property="number" label="编号" align="center" />
          <el-table-column align="center" label="头像">
            <template #default="{ row }">
              <img :src="'http://127.0.0.1:3000/' + row.picture" style="width: 40px" />
            </template>
          </el-table-column>

          <el-table-column property="tname" label="团队名称" align="center" />
          <el-table-column property="dname" label="团队长" align="center" />
          <el-table-column label="团队标签" align="center">
            <template #default="{ row }">
              <div v-for="item in row.labelArr" :key="item">
                {{ item.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column property="oname" label="所属机构" align="center" />
          <el-table-column property="signCount" label="签约人数" align="center" />
          <el-table-column property="score" label="评分" align="center" />
          <el-table-column label="状态" property="status">
            <template #default="{ row }">
              <el-switch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用"
                @click="changeTeamStatus(row)" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <span class="origation-edit" @click="applyToJoin(row)">申请加入</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 确认解散的弹窗 -->

    <el-dialog v-model="centerDialogVisible" title="解散确认" width="30%" align-center>
      <template #title>
        <span>解散确认</span>
        <el-icon name="el-icon-question"></el-icon>
      </template>
      <span style="color: gray; font-size: 30px">确定解散该团队吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sureDel"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 加入团队的弹窗 -->
    <el-dialog v-model="sureJoin" title="确认加入吗" width="30%" align-center>
      <template #title>
        <span>加入确认</span>
        <el-icon name="el-icon-question"></el-icon>
      </template>
      <span style="color: gray; font-size: 30px">确认加入该团队吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sureJoin = false">取消</el-button>
          <el-button type="primary" @click="sureToJoin"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import api from '@/api'

import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'

// 导入分页器
import Fenye from '@/components/zxy/Fenye.vue'
import { getExcel } from '@/utils/yzy/Excel'

// 导入状态机
import teamStore from '@/store/zxy/team'
const store = teamStore()
const { changeInfo } = store

// 查找的功能
const value3 = ref()


// daochu
let tabledata = ref<Array<any>>([])

// 定义一个变量数组
let options = ref([])
let arr = ref<Array<any>>([])
// 获取slect的机构数据
const getOptions = async () => {
  const res = await api.team.getAllChcsOrgan()
  // console.log('获取的机构数据', res.data.data.rows)
  options.value = res.data.data.rows
  options.value.forEach((item: any) => {
    arr.value.push({
      name: item.name,
      id: item.id,
    })
  })
}

// 机构管理绑定的值
const value = ref('')

const activeIndex = ref('0')

// 获取所有的表格

// 查询表格所有的数据
// 获取所有数据的函数参数
const getAllDataObj = ref({
  doctorId: '',
  status: 0,
  organId: '',
  searchKey: '',
  // 分页器
  page: 1,
  count: 5,
})
const getAllData = async () => {
  let result = await api.systemSetting.doctor.getDoctorDetailApi(localStorage.getItem('user_id'))
  getAllDataObj.value.doctorId = result.data.data.id
  // getAllDataObj.value.doctorId = doctorId

  const res = await api.team.getAllTeamApi(getAllDataObj.value)
  tabledata.value = res.data.data.result.reverse()
  console.log('获取的所有的数据', res.data.data)
  // 给分页器赋值
  total.value = res.data.data.total
}

// 切换管理的团队和加入的团队
const handleSelect = (key: string) => {
  if (key === '0') {
    getAllDataObj.value.status = 0
    // 清空select框的value
    value.value = ''
    getAllData()
  } else {
    getAllDataObj.value.status = 1
    getAllData()
    // 清空select框的value
    value.value = ''
  }
  // console.log(key)
}

// 增加医生团队
const router = useRouter()
const addTeam = () => {
  router.push('addTeam')
}

onMounted(() => {
  // 获取select框所有机构的函数
  getOptions()
})

//  获取label的参数
// let getLabelData = ref<getLabelType>({
//   searchKey: '',
//   page: 1,
//   count: 10,
// })

// 当机构变化时候重新获取表格数据
const getLabel = (s: string) => {
  // console.log('orgnaid/', s)
  // 使用变化后获取到的id值进行获取团队信息
  getAllDataObj.value.organId = s
  console.log('change', getAllDataObj.value)
  getAllData()
  // 
  // getAllDataObj.value.organId = ''
}

// 按照关键字查找
const keywords_1 = ref('')
const searchByKeywords = () => {
  getAllDataObj.value.searchKey = keywords_1.value
  getAllData()
  // console.log('查找', keywords_1.value)
}

// 分页器所需的参数
const total = ref<number>(0)
// 分页器传回来的参数
// 获取页码的大小
const getPageSize = (val: number) => {
  // console.log('number', val)
  getAllDataObj.value.count = val
  getAllData()
}

// 获取当前页
const getCurrentPage = (val: number) => {
  // console.log('currentPage---->', val)
  getAllDataObj.value.page = val
  getAllData()
}

//更新团队的启用状态
const statusObj = ref({
  id: '',
  flag: 0,
})
const changeTeamStatus = async (s: any) => {
  console.log('切换状态的', s)
  console.log('bool', s.flag)
  if (s.flag) {
    statusObj.value.flag = 0
  } else {
    statusObj.value.flag = 1
  }
  statusObj.value.id = s.id
  console.log('参数', statusObj.value)
  const res = await api.team.changeTeamAtatusApi(statusObj.value)
  if (res.data.code === 200) {
    ElMessage({
      message: res.data.msg,
      grouping: true,
      type: 'success',
    })
  } else {
    ElMessage({
      message: res.data.msg,
      grouping: true,
      type: 'error',
    })
  }
}

// 解散团队
const delTeamObj = ref({
  id: '',
})
const delTeam = async (s: any) => {
  centerDialogVisible.value = true
  delTeamObj.value.id = s.id
}

// 遮罩层
const dialogVisible = ref(false)
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定关闭?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

// 申请加入的弹窗值
const sureJoin = ref(false)

// 申请加入的参数
const applyToJoinObj = ref({
  teamId: '',
  doctorId: '',
})
const doctorId = localStorage.getItem('user_id')
// 点击申请加入的函数
const applyToJoin = (s: any) => {
  //打开确认加入的弹窗
  sureJoin.value = true
  applyToJoinObj.value.teamId = s.id
  // 本地存储的值赋给
  if (doctorId !== null && doctorId !== undefined) {
    applyToJoinObj.value.doctorId = doctorId
  }

  //  console.log('加入的参数', applyToJoinObj.value)
}
// 点击弹窗的确认加入
const sureToJoin = async () => {
  // 关闭弹窗
  sureJoin.value = false
  const res = await api.team.joinToTeamApi(applyToJoinObj.value)
  console.log('加入结果', res)
  if (res.data.code === 200) {
    ElMessage({
      message: res.data.msg,
      grouping: true,
      type: 'success',
    })
  } else {
    ElMessage({
      message: res.data.msg,
      grouping: true,
      type: 'warning',
    })
  }
}

// 解散团队确认框
const centerDialogVisible = ref(false)
// 确认删除按钮
const sureDel = async () => {
  const res = await api.team.delTeamByTeamidApi(delTeamObj.value)
  // console.log('---------删除团队----------------', s)
  centerDialogVisible.value = false
  console.log('删除团队的结果', res)
  getAllData()
}

//查看团队详情
const teamStoreObj = ref({
  tname: '',
  picture: '',
  oname: '',
  labelArr: [],
})

const TeamDetail = (arg: any) => {
  // 将此时的状态也加到参数里面，用来判断显示的是管理的还是加入的
  console.log('-----------dddd--dddddd------------', arg.oname)
  const owerId = arr.value.find((item) => item.name == arg.oname).id
  console.log(arr.value)
  const arg2 = { ...arg, status: getAllDataObj.value.status, owerId }

  // 状态机里面存放数据
  teamStoreObj.value.tname = arg.tname
  teamStoreObj.value.picture = arg.picture
  teamStoreObj.value.oname = arg.oname
  teamStoreObj.value.labelArr = arg.labelArr

  changeInfo(teamStoreObj.value)
  // 跳转
  // router.push(`teamDetail?info=${obj}`)
  const obj = JSON.stringify(arg2)
  router.push({ path: 'teamDetail', query: { info: obj } })
}

// 默认进来获取所有数据的函数
getAllData()

// 导出
const daochu = () => {
  getExcel(tabledata.value)
}
</script>

<style scoped>
.team {
  width: 1150px;
  height: 800px;
  margin: auto;
  background-color: #fff;
}

.top-team::before {
  margin-left: 5px;
  margin-top: 5px;
  content: '';
  display: inline-block;
  width: 10px;
  height: 30px;
  background-color: skyblue;
  margin-right: 10px;
  border-radius: 6px;
  vertical-align: middle;
  /* 垂直居中对齐 */
}

.top-team {
  font-size: 20px;
  display: flex;
  align-items: center;
}

.menu-wrapper {
  display: flex;
  flex-grow: 1;
}

.el-menu-demo .el-menu-item {
  text-align: left;
}

.top {
  display: flex;
  align-items: center;
}

/* 搜索 框的样式 */

.team-search {
  display: flex;
  align-items: center;
  margin: 10px;
}

.team-keywords {
  width: 30%;
}

.origation-edit {
  margin-right: 3px;
  color: darkcyan;
  cursor: pointer;
}

.origation-del {
  margin-left: 3px;
  color: red;
  cursor: pointer;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.el-icon:hover {
  cursor: pointer;
}
</style>
